package com.wtx.fitness.controller;

import com.wtx.fitness.common.Result;
import com.wtx.fitness.common.ResultCode;
import com.wtx.fitness.entity.Score;
import com.wtx.fitness.exception.BusinessException;
import com.wtx.fitness.exception.NotFoundException;
import com.wtx.fitness.exception.UnauthorizedException;
import com.wtx.fitness.mapper.ScoreMapper;
import com.wtx.fitness.service.ScoreService;
import com.wtx.fitness.util.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 成绩管理控制器
 */
@RestController
@RequestMapping("/api")
public class ScoreController {

  @Autowired
  private ScoreService scoreService;

  @Autowired
  private ScoreMapper scoreMapper;

  /**
   * 获取所有成绩（管理员权限）
   */
  @GetMapping("/admin/scores")
  public Result<List<Score>> getAllScores() {
    // 验证是否为管理员
    String userType = TokenUtil.getUserType();

    if (userType == null) {
      throw new UnauthorizedException("请先登录");
    }

    if (!"admin".equals(userType)) {
      throw new UnauthorizedException("无权限进行此操作");
    }

    List<Score> scores = scoreService.getAllScores();
    return Result.success(scores);
  }

  /**
   * 学生查询自己的成绩
   */
  @GetMapping("/student/scores")
  public Result<List<Score>> getStudentScores() {
    // 验证是否为学生
    String userType = TokenUtil.getUserType();
    String userId = TokenUtil.getUserId();

    if (userType == null || userId == null) {
      throw new UnauthorizedException("请先登录");
    }

    if (!"student".equals(userType)) {
      throw new UnauthorizedException("无权限进行此操作");
    }

    List<Score> scores = scoreService.getScoresByStuId(userId);
    return Result.success(scores);
  }

  /**
   * 根据ID获取成绩详情
   */
  @GetMapping("/scores/{id}")
  public Result<Score> getScoreById(@PathVariable("id") Integer id) {
    Score score = scoreService.getScoreById(id);
    if (score == null) {
      throw new NotFoundException("成绩记录不存在");
    }

    // 验证权限（学生只能查看自己的成绩）
    String userType = TokenUtil.getUserType();
    String userId = TokenUtil.getUserId();

    if (userType == null || userId == null) {
      throw new UnauthorizedException("请先登录");
    }

    if ("student".equals(userType) && !userId.equals(score.getStuId())) {
      throw new UnauthorizedException("只能查看自己的成绩");
    }

    return Result.success(score);
  }

  /**
   * 根据学生ID获取成绩（管理员权限）
   */
  @GetMapping("/admin/scores/student/{stuId}")
  public Result<List<Score>> getScoresByStudentId(@PathVariable("stuId") String stuId) {
    // 验证是否为管理员
    String userType = TokenUtil.getUserType();

    if (userType == null) {
      throw new UnauthorizedException("请先登录");
    }

    if (!"admin".equals(userType)) {
      throw new UnauthorizedException("无权限进行此操作");
    }

    List<Score> scores = scoreService.getScoresByStuId(stuId);
    return Result.success(scores);
  }

  /**
   * 检查学生是否有成绩记录（管理员权限）
   */
  @GetMapping("/admin/scores/check/{stuId}")
  public Result<Boolean> checkStudentHasScores(@PathVariable("stuId") String stuId) {
    // 验证是否为管理员
    String userType = TokenUtil.getUserType();

    if (userType == null) {
      throw new UnauthorizedException("请先登录");
    }

    if (!"admin".equals(userType)) {
      throw new UnauthorizedException("无权限进行此操作");
    }

    boolean hasScores = scoreService.hasScoresByStuId(stuId);
    return Result.success(hasScores);
  }

  /**
   * 根据项目ID获取成绩
   */
  @GetMapping("/scores/item/{itemId}")
  public Result<List<Score>> getScoresByItemId(@PathVariable("itemId") Integer itemId) {
    // 验证是否为管理员
    String userType = TokenUtil.getUserType();

    if (userType == null) {
      throw new UnauthorizedException("请先登录");
    }

    if (!"admin".equals(userType)) {
      throw new UnauthorizedException("无权限进行此操作");
    }

    List<Score> scores = scoreService.getScoresByItemId(itemId);
    return Result.success(scores);
  }

  /**
   * 获取合格率统计（管理员权限）
   */
  @GetMapping("/admin/scores/pass-rate")
  public Result<List<Map<String, Object>>> getPassRateByGender() {
    // 验证是否为管理员
    String userType = TokenUtil.getUserType();

    if (userType == null) {
      throw new UnauthorizedException("请先登录");
    }

    if (!"admin".equals(userType)) {
      throw new UnauthorizedException("无权限进行此操作");
    }

    List<Map<String, Object>> passRates = scoreService.getPassRateByGender();
    return Result.success(passRates);
  }

  /**
   * 获取项目成绩分布（管理员权限）
   */
  @GetMapping("/admin/scores/distribution/{itemId}")
  public Result<List<Map<String, Object>>> getScoreDistribution(@PathVariable("itemId") Integer itemId) {
    // 验证是否为管理员
    String userType = TokenUtil.getUserType();

    if (userType == null) {
      throw new UnauthorizedException("请先登录");
    }

    if (!"admin".equals(userType)) {
      throw new UnauthorizedException("无权限进行此操作");
    }

    List<Map<String, Object>> distribution = scoreService.getScoreDistribution(itemId);
    return Result.success(distribution);
  }

  /**
   * 添加成绩（管理员权限）
   */
  @PostMapping("/admin/scores")
  public Result<Score> addScore(@RequestBody Score score) {
    // 验证是否为管理员
    String userType = TokenUtil.getUserType();

    if (userType == null) {
      throw new UnauthorizedException("请先登录");
    }

    if (!"admin".equals(userType)) {
      throw new UnauthorizedException("无权限进行此操作");
    }

    // 验证必填参数
    if (score.getStuId() == null || score.getStuId().trim().isEmpty()) {
      throw new BusinessException(ResultCode.PARAM_ERROR, "学生ID不能为空");
    }

    if (score.getItemId() == null) {
      throw new BusinessException(ResultCode.PARAM_ERROR, "项目ID不能为空");
    }

    if (score.getStorageValue() == null) {
      throw new BusinessException(ResultCode.PARAM_ERROR, "成绩数值不能为空");
    }

    try {
      int result = scoreService.addScore(score);
      if (result <= 0) {
        throw new BusinessException(ResultCode.SYSTEM_ERROR, "添加成绩失败");
      }
      return Result.success(score);
    } catch (IllegalArgumentException e) {
      throw new BusinessException(ResultCode.PARAM_ERROR, e.getMessage());
    }
  }

  /**
   * 批量添加成绩（管理员权限）
   */
  @PostMapping("/admin/scores/batch")
  public Result<Void> batchAddScores(@RequestBody List<Score> scores) {
    // 验证是否为管理员
    String userType = TokenUtil.getUserType();

    if (userType == null) {
      throw new UnauthorizedException("请先登录");
    }

    if (!"admin".equals(userType)) {
      throw new UnauthorizedException("无权限进行此操作");
    }

    if (scores == null || scores.isEmpty()) {
      throw new BusinessException(ResultCode.PARAM_ERROR, "成绩数据不能为空");
    }

    try {
      int result = scoreService.batchAddScores(scores);
      if (result <= 0) {
        throw new BusinessException(ResultCode.SYSTEM_ERROR, "批量添加成绩失败");
      }
      return Result.success();
    } catch (IllegalArgumentException e) {
      throw new BusinessException(ResultCode.PARAM_ERROR, e.getMessage());
    }
  }

  /**
   * 更新成绩（管理员权限）
   */
  @PutMapping("/admin/scores/{id}")
  public Result<Void> updateScore(@PathVariable("id") Integer id, @RequestBody Score score) {
    // 验证是否为管理员
    String userType = TokenUtil.getUserType();

    if (userType == null) {
      throw new UnauthorizedException("请先登录");
    }

    if (!"admin".equals(userType)) {
      throw new UnauthorizedException("无权限进行此操作");
    }

    if (id == null) {
      throw new BusinessException(ResultCode.PARAM_ERROR, "成绩ID不能为空");
    }

    score.setId(id);

    try {
      int result = scoreService.updateScore(score);
      if (result <= 0) {
        throw new BusinessException(ResultCode.SYSTEM_ERROR, "更新成绩失败");
      }
      return Result.success();
    } catch (IllegalArgumentException e) {
      throw new BusinessException(ResultCode.PARAM_ERROR, e.getMessage());
    }
  }

  /**
   * 删除成绩（管理员权限）
   */
  @DeleteMapping("/admin/scores/{id}")
  public Result<Void> deleteScore(@PathVariable("id") Integer id) {
    // 验证是否为管理员
    String userType = TokenUtil.getUserType();

    if (userType == null) {
      throw new UnauthorizedException("请先登录");
    }

    if (!"admin".equals(userType)) {
      throw new UnauthorizedException("无权限进行此操作");
    }

    if (id == null) {
      throw new BusinessException(ResultCode.PARAM_ERROR, "成绩ID不能为空");
    }

    try {
      int result = scoreService.deleteScore(id);
      if (result <= 0) {
        throw new BusinessException(ResultCode.SYSTEM_ERROR, "删除成绩失败");
      }
      return Result.success();
    } catch (Exception e) {
      throw new BusinessException(ResultCode.SYSTEM_ERROR, "删除成绩失败：" + e.getMessage());
    }
  }

  /**
   * 删除学生所有成绩（管理员权限）
   */
  @DeleteMapping("/admin/scores/student/{stuId}")
  public Result<Void> deleteScoresByStudent(@PathVariable("stuId") String stuId) {
    // 验证是否为管理员
    String userType = TokenUtil.getUserType();

    if (userType == null) {
      throw new UnauthorizedException("请先登录");
    }

    if (!"admin".equals(userType)) {
      throw new UnauthorizedException("无权限进行此操作");
    }

    if (stuId == null || stuId.trim().isEmpty()) {
      throw new BusinessException(ResultCode.PARAM_ERROR, "学生ID不能为空");
    }

    try {
      int result = scoreService.deleteScoresByStuId(stuId);
      return Result.success();
    } catch (Exception e) {
      throw new BusinessException(ResultCode.SYSTEM_ERROR, "删除学生成绩失败：" + e.getMessage());
    }
  }

  /**
   * 统计成绩总数（管理员权限）
   */
  @GetMapping("/admin/score/count")
  public Result<Integer> countScores() {
    // 验证是否为管理员
    String userType = TokenUtil.getUserType();

    if (userType == null) {
      throw new UnauthorizedException("请先登录");
    }

    if (!"admin".equals(userType)) {
      throw new UnauthorizedException("无权限进行此操作");
    }

    int count = scoreMapper.countAll();
    return Result.success(count);
  }
}